<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 5                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available through the world-wide-web at the following url:           |
// | http://www.php.net/license/3_0.txt.                                  |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Original Author <author@example.com>                        |
// |          Your Name <you@example.com>                                 |
// +----------------------------------------------------------------------+
//

/*token验证*/
//function tokencheck($appid,$appkey){
//    global $db;
//    $array_check = array('appid'=>'baisen','appkey'=>'baisennjkhghkjhgbvu7y7y8f5d3');
//    if($appid == $array_check['appid'] and $appkey == $array_check['appkey']){
//        $data = $db->row_select_one('token', "id=1");
//        $token =  $rand = md5(time() . mt_rand(0,1000));
//        if($data){
//            if($data['addtime']-time()>120){
//                $rs = $db -> row_update('token', array('token' => $token,'addtime' => time()), "id=1");
//            }
//        }
//        else{
//            $rs = $db -> row_insert('token', array('token' => $token,'addtime' => time()));
//        }
//        $tokendata = $db->row_select_one('token', "id=1");
//        $tokenvalue = array('token'=>$tokendata['token']);
//    }
//    else{
//        $tokenvalue = array('token'=>'');
//    }
//    $jsonlist = json_encode($tokenvalue);
//    return $jsonlist;
//}

/**
 * 会员登录
 *
 * @param  $username 用户名
 * @param  $password 密码
 */
function user_login($username, $password)
{
    global $db;
    $rs = $db->row_select_one('member', "mobilephone='" . $username . "' AND password='" . $password . "'", 'id,mobilephone,isdealer,ischeck,regtime,isIm,avatar,nicname,company');
    if (!$rs) {
        $status = array(
            'succ' => 'false',
            'msg' => '用户名或密码错误'
        );
    } else {
        $user_valid = $db->row_select_one('member_valid', "member_id=" . $rs['id'], 'id,start_date,end_date', 'id desc');
        //$valid 1 未过期，2 过期
        if ($user_valid) {
            if (time() < $user_valid['end_date']) {
                $valid = 1;
                $valid_date = ceil(($user_valid['end_date'] - time()) / 86400);
                $valid_times = $user_valid['end_date'];
            } else {
                $valid = 2;
                $valid_date = 0;
                $valid_times = 0;
            }
        } else {
            $valid_time = MEMBER_VALID_TIME * 2592000 + $rs['regtime'];
            if (time() < $valid_time) {
                $valid = 1;
                $valid_date = ceil(($valid_time - time()) / 86400);
                $valid_times = $valid_time;
            } else {
                $valid = 2;
                $valid_date = 0;
                $valid_times = 0;
            }
        }
        if ($valid == 2) return json_encode(array('succ' => 'false', 'msg' => '您的会员有效期已过期，请及时联系管理员'));
        $avtar = $rs['avatar'] != "''" ? 'http://' . $_SERVER['HTTP_HOST'] . $rs['avatar'] : '';
        $status = array(
            'succ' => 'true',
            'msg' => '成功',
            'mobilephone' => $rs['mobilephone'],
            'userid' => $rs['id'],
            'isdealer' => $rs['isdealer'],
            'ischeck' => $rs['ischeck'],
            'tel' => '4000-797-555',
            'valid' => $valid,
            'valid_date' => $valid_date,
            'valid_time' => $valid_times,
            'isIm' => $rs['isIm'],
            'avatar' => $avtar,
            'nicname' =>$rs['nicname'],
            'company' =>$rs['company']
        );
    }
    $jsonlist = json_encode($status);
    return $jsonlist;
}

/**
 * 验证用户名是否被注册
 *
 * @param  $username 用户名
 */
function user_register_username($username)
{
    global $db;
    $rs = $db->row_count('member', "username='" . $username . "'");
    if (!$rs) {
        $status = array(
            'succ' => 'true',
            'msg' => '用户名验证成功'
        );
    } else {
        $status = array(
            'succ' => 'false',
            'msg' => '此用户已被注册！'
        );
    }

    $jsonlist = json_encode($status);
    return $jsonlist;
}

/**
 * 验证手机号是否被注册
 *
 * @param  $username 用户名
 */
function user_register_mobilephone($mobilephone)
{
    global $db;
    $rs = $db->row_count('member', "mobilephone='" . $mobilephone . "'");
    if (!$rs) {
        $status = array(
            'succ' => 'true',
            'msg' => '手机号验证成功'
        );
    } else {
        $status = array(
            'succ' => 'false',
            'msg' => '此手机号已被注册！'
        );
    }

    $jsonlist = json_encode($status);
    return $jsonlist;
}

/**
 * 会员注册
 *
 * @param  $username 用户名
 * @param  $password 密码
 */
function user_register($password, $nicname, $mobilephone, $email, $company, $aid, $cid, $code)
{
    global $db;
    $post['password'] = trim($password);
    $post['nicname'] = trim($nicname);
    $post['mobilephone'] = trim($mobilephone);
    $post['email'] = trim($email);
    $post['company'] = trim($company);
    $post['isdealer'] = 2; //商家
    $post['aid'] = intval($aid);
    $post['cid'] = intval($cid);
    $post['regtime'] = TIMESTAMP;
    // $post['isIm'] = $isIm;

    if (empty($post['mobilephone'])) return json_encode(array('succ' => 'false', 'msg' => '手机号不可为空'));
    if (empty($code)) return json_encode(array('succ' => 'false', 'msg' => '验证码不可为空'));
    $record = $db->row_select_one('sms_records', "mobile='" . $post['mobilephone'] . "' and type=1", '*', 'id desc');
    if (!$record) return json_encode(array('succ' => 'false', 'msg' => '验证码不存在'));
    list($Code, $Time) = explode('_', $record['code']);
    if ($Code != $code) return json_encode(array('succ' => 'false', 'msg' => '验证码错误'));
    if (time() - intval($Time) > SMS_CODE_TIME) return json_encode(array('succ' => 'false', 'msg' => '验证码已过期'));

    $rs = $db->row_count('member', "mobilephone='" . $post['mobilephone'] . "'");
    if ($rs) {
        $status = array(
            'succ' => 'false',
            'msg' => '用户名或手机号已被注册！'
        );
    } else {
        $rs = $db->row_insert('member', $post);
        if (!$rs) {
            $status = array(
                'succ' => 'false',
                'msg' => '失败'
            );
        } else {
            $member_id = $db->insert_id();
            $end_date = MEMBER_VALID_TIME * 2592000 + $post['regtime'];
            $db->row_insert('member_valid', array('member_id' => $member_id, 'start_date' => $post['regtime'], 'end_date' => $end_date));
            $status = array(
                'succ' => 'true',
                'msg' => '成功',
                'uid' => $member_id
            );
        }
    }
    $jsonlist = json_encode($status);
    return $jsonlist;
}

//修改密码
function user_modifypwd($uid, $oldpwd, $newpwd)
{
    global $db;
    $uid = intval($uid);
    $post['password'] = trim($newpwd);
    $rs = $db->row_select_one('member', "id=" . $uid . ' and password=' . "'" . md5($oldpwd) . "'");
    if ($rs) {
        $rs = $db->row_update('member', array('password' => $post['password']), "id=" . $uid);
        if ($rs) {
            $status = array(
                'succ' => 'true',
                'msg' => '修改密码成功！'
            );
        } else {
            $status = array(
                'succ' => 'false',
                'msg' => '修改密码失败！'
            );
        }
    } else {
        $status = array(
            'succ' => 'false',
            'msg' => '旧密码错误！'
        );
    }
    $jsonlist = json_encode($status);
    return $jsonlist;
}

//返回商家类型
function select_dealertype()
{
    global $db;
    $dealertype_arr['list'] = array();
    $list = $db->row_select('dealer_category', "1=1", 'id,catname', 0, 'orderid asc');
    foreach ($list as $key => $value) {
        $dealertype_arr['list'][$key]['id'] = $value['id'];
        $dealertype_arr['list'][$key]['name'] = $value['catname'];
    }
    return json_encode($dealertype_arr);
}

/**
 * 查询用户信息
 */
function get_user($id)
{
    global $db;
    $data = $db->row_select_one('member', "id=" . $id, 'cid,aid did,dno,username,nicname,email,usertype,userstate,userlevel,regtime,regip,last_login_time,last_login_ip,login_count,tel,mobilephone,fax,address,qq,company,logo,shopdetail,ischeck,isdealer');
    $jsonlist = json_encode($data);
    return $jsonlist;
}

// $Id:$

/**
 * 查询车源
 *
 * @param  $page 页码
 * @param  $status 类型(1:最新, 2:热门, 3:推荐)
 */
function search_cars($status = '', $page = '', $brand = '', $subbrand = '', $price = '', $age = '', $kilometre = '', $transmission = '', $gas = '', $color = '', $source = '', $class = '', $picture = '', $aid = '', $cid = '', $uid = '', $keywords = '', $mobilecode = '', $identify = '', $tel = '', $code = '', $sameprice = '', $samebrand = '', $comparcode)
{
    global $db;
    $orderby = 'issell asc,issprecom desc,';
    $where = "isshow=1";
    if (!empty($status)) {
        switch ($status) {
            case 1:
                $orderby .= "listtime desc";
                break;

            case 2:
                $orderby .= "  p_price asc";
                break;

            case 3:
                $orderby .= "  p_price desc";
                break;

            case 4:
                $orderby .= "  p_kilometre ";
                break;

            case 5:
                $orderby .= "  p_year desc, p_month desc";
                break;
        }
    }
    if (!empty($brand)) $where .= " and p_brand=" . $brand;
    if (!empty($sameprice)) {
        $pc = 5;
        $where .= " and p_price> " . ($sameprice - $pc) . " and p_price< " . ($sameprice + $pc);
    }
    if (!empty($samebrand)) $where .= " and p_brand=" . $samebrand;
    if (!empty($keywords)) $where .= " and p_allname  like '" . $keywords . "%' ";
    if (!empty($subbrand)) $where .= " and p_subbrand=" . $subbrand;
    if (!empty($cid)) $where .= " and cid=" . $cid;
    if (!empty($aid)) $where .= " and aid=" . $aid;
    if (!empty($class)) $where .= " and p_model=" . $class;


    //返回我的车源对比信息
    if (!empty($comparcode)) {
        $data = $db->row_select_one('comparison', "mobilecode=" . $comparcode);
        if ($data['mobilecode'] == '') {
            $where .= " and p_id in (select p_id from contrastcars where mobilecode=" . $comparcode . ")";
        } else {
            $tel = $data['mobilephone'];
            $where .= " and p_id in (select p_id from contrastcars where mobilecode=" . $comparcode . ")" . " or p_id=(select p_id from contrastcars where mobilephone=" . $tel . ")";
        }
    }

    //返回我的车源收藏信息
    if (!empty($uid)) {
        $where .= " and p_id in (select p_id from simcms_collectcars where  uid=" . $uid . ")";
    }

    //查询我的发布车源
    if (!empty($code)) {
        $data = $db->row_select('comparison', "mobilecode=" . '"' . $code . '"');
        if ($data[0]['mobilecode'] == '') {
            $where .= " and mobilecode=" . '"' . $code . '"';
        } else {
            $tel = $data[0]['mobilephone'];
            $where .= " and mobilecode=" . '"' . $code . '"' . " and mobilephone=" . $tel;
        }
    }

    if (!empty($identify)) $where .= " and identify=" . $identify;
    if (!empty($age)) {
        $compareyear01 = date("Y");
        switch ($age) {
            case 0:
                $where .= "";
                break;

            case 1:
                $ages = $compareyear01 - 1;
                $where .= " and  p_year>" . $ages;
                break;

            case 2:
                $agesup = $compareyear01 - 1;
                $agesdown = $compareyear01 - 3;
                $where .= " and  p_year<= " . $agesup . " and p_year>" . $agesdown;
                break;

            case 3:
                $agesup = $compareyear01 - 3;
                $agesdown = $compareyear01 - 5;
                $where .= " and  p_year<= " . $agesup . " and p_year>" . $agesdown;
                break;

            case 4:
                $agesup = $compareyear01 - 5;
                $agesdown = $compareyear01 - 8;
                $where .= " and  p_year<= " . $agesup . " and p_year>" . $agesdown;
                break;

            case 5:
                $agesup = $compareyear01 - 8;
                $agesdown = $compareyear01 - 10;
                $where .= " and  p_year<= " . $agesup . " and p_year>" . $agesdown;
                break;

            case 6:
                $ages = $compareyear01 - 10;
                $where .= " and  p_year< " . $ages;
                break;
        }
    }
    if (!empty($kilometre)) {
        switch ($kilometre) {
            case 0:
                $where .= "";
                break;

            case 1:
                $where .= " and p_kilometre<1 ";
                break;

            case 2:
                $where .= " and  p_kilometre<3";
                break;

            case 3:
                $where .= " and  p_kilometre<5 ";
                break;

            case 4:
                $where .= " and  p_kilometre<10";
                break;

            case 5:
                $where .= " and  p_year>10";
                break;
        }
    }
    if (!empty($price)) {
        switch ($price) {
            case 0:
                $where .= "";
                break;

            case 1:
                $where .= " and  p_price<3 ";
                break;

            case 2:
                $where .= " and p_price>=3 and p_price<5 ";
                break;

            case 3:
                $where .= " and  p_price>=5 and p_price<8 ";
                break;

            case 4:
                $where .= " and p_price>=8 and p_price<12";
                break;

            case 5:
                $where .= " and p_price>=12 and p_price<18";
                break;

            case 6:
                $where .= " and p_price>=18 and p_price<24";
                break;

            case 7:
                $where .= " and p_price>=24 and p_price<35";
                break;

            case 8:
                $where .= " and p_price>=35 and p_price<60";
                break;

            case 9:
                $where .= " and p_price>=60 and p_price<100";
                break;

            case 10:
                $where .= " and p_price>100";
                break;
            default:
                if (strpos($price, '_')) {
                    list($lower, $higher) = explode('_', $price);
                    $where .= " and p_price>=$lower and p_price<$higher";
                }
        }
    }
    if (!empty($transmission)) {
        switch ($transmission) {
            case 0:
                $where .= "";
                break;

            case 1:
                $where .= " and p_transmission='手动' ";
                break;

            case 2:
                $where .= " and p_transmission='自动' ";
                break;

            case 3:
                $where .= " and  p_transmission='手自一体'  ";
                break;

            case 4:
                $where .= "  and p_transmission='无纺变速' ";
                break;

            case 5:
                $where .= "  and p_transmission='双离合' ";
                break;
        }
    }
    if (!empty($gas)) {
        switch ($gas) {
            case 0:
                $where .= "";
                break;

            case 1:
                $where .= " and p_gas<1.0 ";
                break;

            case 2:
                $where .= " and p_gas>=1.0 and p_gas<1.6 ";
                break;

            case 3:
                $where .= "  and p_gas>=1.6 and p_gas<2.0  ";
                break;

            case 4:
                $where .= " and p_gas>=2.0 and p_gas<3.0 ";
                break;

            case 5:
                $where .= " and p_gas>3.0 ";
                break;
        }
    }
    if (!empty($color)) {
        switch ($color) {
            case 0:
                $where .= "";
                break;

            case 1:
                $where .= " and p_color='黑色' ";
                break;

            case 2:
                $where .= " and p_color='银灰色' ";
                break;

            case 3:
                $where .= " and p_color='白色'  ";
                break;

            case 4:
                $where .= " and p_color='红色' ";
                break;

            case 5:
                $where .= " and p_color='蓝色' ";
                break;

            case 6:
                $where .= " and p_color='深灰色' ";
                break;

            case 7:
                $where .= " and p_color='香槟色' ";
                break;

            case 8:
                $where .= " and p_color='绿色' ";
                break;

            case 9:
                $where .= " and p_color='黄色' ";
                break;

            case 10:
                $where .= " and p_color='橙色' ";
                break;

            case 11:
                $where .= "  and p_color='咖啡色' ";
                break;

            case 12:
                $where .= " and p_color='紫色' ";
                break;

            case 13:
                $where .= " and p_color='多彩色' ";
                break;
        }
    }
    if (!empty($source)) {
        switch ($source) {
            case 0:
                $where .= "";
                break;

            case 1:
                $puser = $db->row_select_one('member', 'isdealer=1', 'id');
                $where .= " and  uid= " . $puser['id'];
                break;

            case 2:
                $suser = $db->row_select_one('member', 'isdealer=2', 'id');
                $where .= " and  uid= " . $suser['id'];
                break;
        }
    }
    if (!empty($picture)) {
        switch ($picture) {
            case 0:
                $where .= "";
                break;
            case 1:
                $where .= " and  p_pics is not null ";
                break;
        }
    }

    $page = !empty($page) ? $page : 1;
    include(INC_DIR . 'Page.class.php');
    $Page = new Page($db->tb_prefix . 'cars', $where, 'uid,p_id,p_allname,p_price,p_color,p_gas,p_kilometre,p_year,p_month,p_mainpic,listtime,issell,isrecom,issprecom,ishot', '10', $orderby);
    $listnum = $Page->total_num;
    $list = $Page->get_data();
    foreach ($list as $key => $value) {
        $list[$key]['id'] = $value['p_id'];
        $list[$key]['carname'] = $value['p_allname'];
        $list[$key]['price'] = $value['p_price'];
        $list[$key]['color'] = $value['p_color'];
        $list[$key]['gas'] = $value['p_gas'];
        $list[$key]['kilometre'] = $value['p_kilometre'];
        //$list[$key]['regdate'] = $value['p_year'] . "年" . $value['p_month'] . '月';
        $list[$key]['regdate'] = $value['p_year'] . "年";
        //$list[$key]['mainpic'] = "http://test.simcms.net".$value['p_mainpic'];
        if (!empty($value['p_mainpic'])) {
            $pic = explode(".", $value['p_mainpic']);
            $list[$key]['mainpic'] = WEB_DOMAIN . $pic[0] . "_small" . "." . $pic[1];
            //$list[$key]['mainpic'] = WEB_DOMAIN.$value['p_mainpic'];

        }
        $list[$key]['listtime'] = date('Y-m-d', $value['listtime']);
        if (!empty($value['cid'])) {
            $area = $db->row_select_one('area', "id=" . $value['cid'], 'name');
            $list[$key]['city'] = $area['name'];
        } else {
            $list[$key]['city'] = "";
        }
        // 商家信息
        if (!empty($value['uid'])) {
            $user = $db->row_select_one('member', 'id=' . $value['uid'], 'isdealer');
            if ($user['isdealer'] == 2) {
                $list[$key]['usertype'] = "商家";
            } else {
                $list[$key]['usertype'] = "个人";
            }
        } else {
            $list[$key]['usertype'] = "个人";
        }
        unset($list[$key]['p_id']);
        unset($list[$key]['p_allname']);
        unset($list[$key]['p_price']);
        unset($list[$key]['p_color']);
        unset($list[$key]['p_gas']);
        unset($list[$key]['p_kilometre']);
        unset($list[$key]['p_year']);
        unset($list[$key]['p_month']);
        unset($list[$key]['p_mainpic']);
        unset($list[$key]['cid']);
    }
    $page_arr = $Page->api_page();
    $carlist = array(
        'page' => $page_arr,
        'list' => $list
    );
    return json_encode($carlist);
}

/*
*收藏车源列表
*$orderby    排序
*$uid        会员id
*$isnewcar   新车二手车
*/
function collect_cars($uid, $orderby)
{
    global $db;
    $where = "isshow=1 and p_id in (select p_id from simcms_collectcars where uid=" . $uid . ")";
    if (!empty($orderby)) {
        switch ($orderby) {
            case 1:
                $order_by = "listtime desc";
                break;

            case 2:
                $order_by = "p_price asc";
                break;

            case 3:
                $order_by = "p_price desc";
                break;

            case 4:
                $order_by = "p_kilometre";
                break;

            case 5:
                $order_by = "p_year desc, p_month desc";
                break;
        }
    } else {
        $order_by = "listtime desc";
    }

    $list = $db->row_select('cars', $where, 'uid,p_id,p_allname,p_price,p_color,p_gas,p_kilometre,p_year,p_month,p_mainpic,listtime', 0, $order_by);
    foreach ($list as $key => $value) {
        $list[$key]['id'] = $value['p_id'];
        $list[$key]['carname'] = $value['p_allname'];
        $list[$key]['price'] = $value['p_price'];
        $list[$key]['color'] = $value['p_color'];
        $list[$key]['gas'] = $value['p_gas'];
        $list[$key]['kilometre'] = $value['p_kilometre'];
        $list[$key]['regdate'] = $value['p_year'] . "年" . $value['p_month'] . '月';
        if (!empty($value['p_mainpic'])) {
            $pic = explode(".", $value['p_mainpic']);
            $list[$key]['mainpic'] = WEB_DOMAIN . $pic[0] . "_small" . "." . $pic[1];
        }
        $list[$key]['listtime'] = date('Y-m-d', $value['listtime']);
        if (!empty($value['cid'])) {
            $area = $db->row_select_one('area', "id=" . $value['cid'], 'name');
            $list[$key]['city'] = $area['name'];
        } else {
            $list[$key]['city'] = "";
        }
        // 商家信息
        if (!empty($value['uid'])) {
            $user = $db->row_select_one('member', 'id=' . $value['uid'], 'isdealer');
            if ($user['isdealer'] == 2) {
                $list[$key]['usertype'] = "商家";
            } else {
                $list[$key]['usertype'] = "个人";
            }
        } else {
            $list[$key]['usertype'] = "个人";
        }
        unset($list[$key]['p_id']);
        unset($list[$key]['p_allname']);
        unset($list[$key]['p_price']);
        unset($list[$key]['p_color']);
        unset($list[$key]['p_gas']);
        unset($list[$key]['p_kilometre']);
        unset($list[$key]['p_year']);
        unset($list[$key]['p_month']);
        unset($list[$key]['p_mainpic']);
        unset($list[$key]['cid']);
    }
    $carlist = array(
        'list' => $list
    );
    return json_encode($carlist);
}

/*
*我发布的车源列表
*$orderby    排序
*$uid        会员id
*$isnewcar   新车二手车
*/
function my_publishcars($uid, $mobilecode, $orderby)
{
    global $db;

    $orderby = '';

    if ($uid != 0) {
        $where = "uid=" . $uid;
    } else {
        if ($mobilecode != '') {
            $where = "mobilecode=" . '"' . $mobilecode . '"';

        }
//		else{
//			$carlist = array(
//				'list' => array()
//			);
//			return json_encode($carlist);
//			exit;
//		}
    }


    if (!empty($orderby)) {
        switch ($orderby) {
            case 1:
                $order_by = "listtime desc";
                break;

            case 2:
                $order_by = "p_price asc";
                break;

            case 3:
                $order_by = "p_price desc";
                break;

            case 4:
                $order_by = "p_kilometre ";
                break;

            case 5:
                $order_by = "p_year desc, p_month desc";
                break;
        }
    } else {
        $order_by = "listtime desc";
    }


    $list = $db->row_select('cars', $where, 'isshow,uid,p_id,p_allname,p_price,p_color,p_gas,p_kilometre,p_year,p_month,p_mainpic,listtime,issell', 0, $order_by);
    foreach ($list as $key => $value) {
        $list[$key]['id'] = $value['p_id'];
        $list[$key]['carname'] = $value['p_allname'];
        $list[$key]['price'] = $value['p_price'];
        $list[$key]['color'] = $value['p_color'];
        $list[$key]['gas'] = $value['p_gas'];
        $list[$key]['kilometre'] = $value['p_kilometre'];
        $list[$key]['regdate'] = $value['p_year'] . "年" . $value['p_month'] . '月';
        if (!empty($value['p_mainpic'])) {
            $pic = explode(".", $value['p_mainpic']);
            $list[$key]['mainpic'] = WEB_DOMAIN . $pic[0] . "_small" . "." . $pic[1];
        }
        $list[$key]['listtime'] = date('Y-m-d', $value['listtime']);
        if (!empty($value['cid'])) {
            $area = $db->row_select_one('area', "id=" . $value['cid'], 'name');
            $list[$key]['city'] = $area['name'];
        } else {
            $list[$key]['city'] = "";
        }
        // 商家信息
        if (!empty($value['uid'])) {
            $user = $db->row_select_one('member', 'id=' . $value['uid'], 'isdealer');
            if ($user['isdealer'] == 2) {
                $list[$key]['usertype'] = "商家";
            } else {
                $list[$key]['usertype'] = "个人";
            }
        } else {
            $list[$key]['usertype'] = "个人";
        }
        unset($list[$key]['p_id']);
        unset($list[$key]['p_allname']);
        unset($list[$key]['p_price']);
        unset($list[$key]['p_color']);
        unset($list[$key]['p_gas']);
        unset($list[$key]['p_kilometre']);
        unset($list[$key]['p_year']);
        unset($list[$key]['p_month']);
        unset($list[$key]['p_mainpic']);
        unset($list[$key]['cid']);
    }
    $carlist = array(
        'list' => $list
    );
    return json_encode($carlist);
}

/**
 * 车源详情
 *
 * @param  $id 车源id
 */
function search_cars_detail($id, $uid)
{
    global $db, $db_config;
    //读取缓存
    $fzz = new fzz_cache;
    if (!($fzz->_isset("common_cache"))) {
        $fzz->set("common_cache", display_common_cache(), CACHETIME);
    }
    $commoncache = $fzz->get("common_cache");
    $array_city = $commoncache['citylist'];
    $array_model = $commoncache['modellist'];
    $array_brand = $commoncache['brandlist']; //一级品牌
    $array_subbrand = $commoncache['subbrandlist']; //二级品牌
    $data = $db->row_select_one('cars', "p_id=" . $id, 'p_id,uid,cid,aid,p_brand,p_subbrand,p_subsubbrand,p_model,p_allname,p_price,p_kilometre,p_transmission,p_color,p_gas,listtime,p_mainpic,p_pics,p_details,p_year,p_month,listtime,p_username,p_tel,p_emission,issell,p_hits,p_surveydate,p_insurancedate ');
    if ($data) {

        if ($uid != $data['uid']) {
            $sql = "UPDATE {$db_config['TB_PREFIX']}cars SET  p_hits=p_hits+1 WHERE p_id=$id";
            @$db->row_query($sql);
        }
        $data['id'] = $data['p_id'];
        $data['carname'] = $data['p_allname'];
        $data['model'] = $array_model[$data['p_model']];
        if (!empty($data['cid'])) {
            $data['city'] = $array_city[$data['cid']];
        } else {
            $data['city'] = "";
        }
        $data['car_brand'] = $data['p_brand'];
        $data['price'] = $data['p_price'];
        $data['color'] = $data['p_color'];
        $data['transmission'] = $data['p_transmission'];
        $data['kilometre'] = $data['p_kilometre'];
        $data['gas'] = $data['p_gas'];
        $data['country'] = $data['p_country'];
        $data['listtime'] = date('Y-m-d', $data['listtime']);
        $data['details'] = $data['p_details'];
        $data['emission'] = $data['p_emission'];
        $data['regdate'] = $data['p_year'] . "年" . $data['p_month'] . '月';
        $data['year'] = $data['p_year'];
        $data['month'] = $data['p_month'];
        $data['mainpic'] = WEB_DOMAIN . $data['p_mainpic'];
        $data['surveydate'] = date('Y-m', $data['p_surveydate']);
        $data['insurancedate'] = date('Y-m', $data['p_insurancedate']);
        $data['tel'] = $data['p_tel'];
        if (!empty($data['p_pics'])) {
            $piclist = explode('|', $data['p_pics']);
            $data['p_pics'] = array_filter($piclist);
            foreach ($data['p_pics'] as $key => $value) {
                $data['p_pics'][$key] = WEB_DOMAIN . $value;
            }
        }
        if ($data['uid'] == 0) {
            $data['username'] = $data['p_username'];
            $data['tel'] = $data['p_tel'];
            $data['usertype'] = "";
            // $data['company'] = "";
//            $data['address'] = "";
//            $publishcars = $db->row_select('cars', "mobilecode=" . $mobilecode, 'p_id');
//            $data['publishcars'] = count($publishcars);
//            $sucars = $db->row_select('cars', "mobilecode=" . $mobilecode . ' and issell=1 ', 'p_id');
//            $data['sucars'] = count($sucars);
        } else {
            $user = $db->row_select_one('member', "id=" . $data['uid'], 'shoptype,id,mobilephone,nicname,isdealer,address,company,isIm');
            $data['username'] = $user['nicname'];
            $data['tel'] = $user['mobilephone'];
            if ($user['isdealer'] == 2) {
                $data['usertype'] = "商家";
                $data['company'] = $user['company'];
                $data['address'] = $user['address'];
                $publisholdcars = $db->row_select('cars', "uid=" . $user['id'], 'p_id');
                $data['publisholdcars'] = count($publisholdcars);
                $suoldcars = $db->row_select('cars', "uid=" . $user['id'] . ' and issell=1 ', 'p_id');
                $data['suoldcars'] = count($suoldcars);
                if ($user['shoptype'] == 1) {
                    $data['shoptypename'] = "经纪公司";
                } else if ($user['shoptype'] == 2) {
                    $data['shoptypename'] = "4S店";
                } else if ($user['shoptype'] == 3) {
                    $data['shoptypename'] = "综合经销商";
                } else {
                    $data['shoptypename'] = "公司经营";
                }
            } else {
                $data['usertype'] = "个人";
                $data['username'] = $user['nicname'];
            }

            $data['isIm'] = $user['isIm'];

        }


        if ($uid != 0) {
            $collectcars = $db->row_select('collectcars', 'uid=' . $uid . ' and p_id=' . $id);
            if ($collectcars) {
                $data['iscollect'] = 1;
            } else {
                $data['iscollect'] = 0;
            }
            $collectmember = $db->row_select('collectmember', 'dealerid=' . $data['uid'] . ' and uid=' . $uid);
            if ($collectmember) {
                $data['ismemcollect'] = 1;
            } else {
                $data['ismemcollect'] = 0;
            }
        } else {
            $data['iscollect'] = 0;
            $data['ismemcollect'] = 0;
        }

        unset($data['p_id']);
        //unset($data['uid']);
        unset($data['p_allname']);
        unset($data['p_price']);
//        unset($data['p_transmission']);
        unset($data['p_gas']);
        unset($data['p_country']);
        unset($data['p_mainpic']);
        unset($data['p_kilometre']);
        unset($data['p_details']);
        unset($data['p_year']);
        unset($data['p_tel']);
        unset($data['p_month']);
        unset($data['p_color']);
        unset($data['p_username']);
        unset($data['p_emission']);
//		unset($data['p_surveydate']);
//		unset($data['p_insurancedate']);
    }
//    echo "<pre>";
//    var_dump($data);exit;
    return json_encode($data);
}

//车源二、三级品牌
function select_secondbrands($brand)
{
    global $db;
    //if(!empty($brand)){
    //	$sublist = $db -> row_select('brand', "b_name= like '%" . $brand . "%'" , 'b_id,b_name', 0, 'orderid asc');
    //}else{
    $list = $db->row_select('brand', "b_parent=" . $brand, 'b_id,b_name,mark,pic');
    foreach ($list as $key => $value) {
        $list[$key]['b_id'] = $value['b_id'];
        $list[$key]['b_name'] = trim($value['b_name']);
        $list[$key]['mark'] = $value['mark'];
        $list[$key]['pic'] = "";
        $sublist = $db->row_select('brand', "b_parent=" . $value['b_id'], 'b_id,b_name', 0, 'orderid asc');
        foreach ($sublist as $k => $v) {
            //$k++;
            $sublist[$k]['b_name'] = trim($v['b_name']);
            $sublist[$k]['b_id'] = trim($v['b_id']);
        }
//        $sublist[0]['b_name'] = '不限';
//        $sublist[0]['b_id'] = 0;
        $list[$key]['subbrand'] = $sublist;
    }
    //}
    //$jsonlist = JSON($list);
    //	return $jsonlist;
//        echo "<pre>";
//    var_dump($list);exit;
    return json_encode($list);
}

//车源一级品牌
function select_brands()
{
    global $db;
    $list = $db->row_select('brand', "b_parent=-1", 'b_id,b_name,mark,pic');
    foreach ($list as $key => $value) {
        $list[$key + 1]['b_id'] = $value['b_id'];
        $list[$key + 1]['b_name'] = trim($value['b_name']);
        $list[$key + 1]['mark'] = $value['mark'];
        if (!empty($value['pic'])) {
            $list[$key + 1]['icon'] = WEB_DOMAIN . "/upload/brand/" . $value['pic'];
            $list[$key + 1]['pic'] = WEB_DOMAIN . "/upload/brand/" . $value['pic'];
        } else {
            $list[$key + 1]['icon'] = "";
            $list[$key + 1]['pic'] = "";
        }
    }
    $list[0]['b_name'] = "不限品牌";
    $list[0]['b_id'] = 0;
    $list[0]['mark'] = "B";
    $list[0]['pic'] = "";
    $list[0]['icon'] = "";
//    echo "<pre>";
//    var_dump($list);exit;
    return json_encode($list);
}

/*筛选参数*/
function select_option()
{
    global $db;
    $settings = settings();
    $array_option = array();
    $array_option['price'] = array(
        array(
            'id' => 0,
            'name' => '不限',
        ),
        array(
            'id' => 1,
            'name' => '3万以下',
        ),
        array(
            'id' => 2,
            'name' => '3-5万',
        ),
        array(
            'id' => 3,
            'name' => '5-8万',
        ),
        array(
            'id' => 4,
            'name' => '8-12万',
        ),
        array(
            'id' => 5,
            'name' => '12-18万',
        ),
        array(
            'id' => 6,
            'name' => '18-24万',
        ),
        array(
            'id' => 7,
            'name' => '24-35万',
        ),
        array(
            'id' => 8,
            'name' => '35-60万',
        ),
        array(
            'id' => 9,
            'name' => '60-100万',
        ),
        array(
            'id' => 10,
            'name' => '100万以上',
        )
    );
    $array_option['age'] = array(
        array(
            'id' => '0',
            'name' => '不限'
        ),
        array(
            'id' => '1',
            'name' => '1年以内'
        ),
        array(
            'id' => '2',
            'name' => '1-3年'
        ),
        array(
            'id' => '3',
            'name' => '3-5年'
        ),
        array(
            'id' => '4',
            'name' => '5-8年'
        ),
        array(
            'id' => '5',
            'name' => '8-10年'
        ),
        array(
            'id' => '6',
            'name' => '10年以上'
        )
    );
    $array_option['kilometre'] = array(
        array(
            'id' => '0',
            'name' => '不限'
        ),
        array(
            'id' => '1',
            'name' => '1万公里以下'
        ),
        array(
            'id' => '2',
            'name' => '3万公里以下'
        ),
        array(
            'id' => '3',
            'name' => '5万公里以下'
        ),
        array(
            'id' => '4',
            'name' => '10万公里以下'
        ),
        array(
            'id' => '5',
            'name' => '10万公里以上'
        )
    );
    $array_option['transmission'] = array(
        array(
            'id' => '0',
            'name' => '不限'
        ),
        array(
            'id' => '1',
            'name' => '手动'
        ),
        array(
            'id' => '2',
            'name' => '自动'
        ),
        array(
            'id' => '3',
            'name' => '手自一体'
        ),
        array(
            'id' => '4',
            'name' => '无极变速'
        ),
        array(
            'id' => '5',
            'name' => '双离合'
        )
    );
    $array_option['gas'] = array(
        array(
            'id' => '0',
            'name' => '不限'
        ),
        array(
            'id' => '1',
            'name' => '1.0以下'
        ),
        array(
            'id' => '2',
            'name' => '1.0'
        ),
        array(
            'id' => '3',
            'name' => '1.2'
        ),
        array(
            'id' => '4',
            'name' => '1.3'
        ),array(
            'id' => '5',
            'name' => '1.4'
        ),
        array(
            'id' => '6',
            'name' => '1.4T'
        ),
        array(
            'id' => '7',
            'name' => '1.5'
        ),
        array(
            'id' => '8',
            'name' => '1.6'
        ),
        array(
            'id' => '9',
            'name' => '1.8'
        ),
        array(
            'id' => '10',
            'name' => '1.8T'
        ),
        array(
            'id' => '11',
            'name' => '2.0'
        ),
        array(
            'id' => '12',
            'name' => '2.0T'
        ),
        array(
            'id' => '13',
            'name' => '2.3'
        ),
        array(
            'id' => '14',
            'name' => '2.4'
        ),
        array(
            'id' => '15',
            'name' => '2.5'
        ),
        array(
            'id' => '16',
            'name' => '3.0'
        ),
        array(
            'id' => '17',
            'name' => '3.0T'
        ),
        array(
            'id' => '18',
            'name' => '4.4'
        ),
        array(
            'id' => '19',
            'name' => '5.0'
        ),
        array(
            'id' => '20',
            'name' => '6.2'
        )
    );
    $array_option['color'] = array(
        array(
            'id' => '0',
            'name' => '不限'
        ),
        array(
            'id' => '1',
            'name' => '黑色'
        ),
        array(
            'id' => '2',
            'name' => '银灰色'
        ),
        array(
            'id' => '3',
            'name' => '白色'
        ),
        array(
            'id' => '4',
            'name' => '红色'
        ),
        array(
            'id' => '5',
            'name' => '蓝色'
        ),
        array(
            'id' => '6',
            'name' => '深灰色'
        ),
        array(
            'id' => '7',
            'name' => '香槟色'
        ),
        array(
            'id' => '8',
            'name' => '绿色'
        ),
        array(
            'id' => '9',
            'name' => '黄色'
        ),
        array(
            'id' => '10',
            'name' => '橙色'
        ),
        array(
            'id' => '11',
            'name' => '咖啡色'
        ),
        array(
            'id' => '12',
            'name' => '紫色'
        ),
        array(
            'id' => '13',
            'name' => '多彩色'
        )
    );
    $array_option['source'] = array(
        array(
            'id' => '0',
            'name' => '不限'
        ),
        array(
            'id' => '1',
            'name' => '个人'
        ),
        array(
            'id' => '2',
            'name' => '商家'
        )
    );
    $array_option['source'] = array(
        array(
            'id' => '0',
            'name' => '不限'
        ),
        array(
            'id' => '1',
            'name' => '个人'
        ),
        array(
            'id' => '2',
            'name' => '商家'
        )
    );

    $array_option['model'] = $db->row_select('model', "1=1", 's_id,s_name', 0, 'orderid asc');
    foreach ($array_option['model'] as $key => $value) {
        $array_option['model'][$key + 1]['id'] = $value['s_id'];
        $array_option['model'][$key + 1]['name'] = trim($value['s_name']);
        unset($array_option['model'][$key + 1]['s_id']);
        unset($array_option['model'][$key + 1]['s_name']);
    }
    $array_option['model'][0]['id'] = 0;
    $array_option['model'][0]['name'] = '不限';
    unset($array_option['model'][0]['s_id']);
    unset($array_option['model'][0]['s_name']);

    $array_option['country'] = array(
        array(
            'id' => '0',
            'name' => '不限'
        ),
        array(
            'id' => '1',
            'name' => '国产'
        ),
        array(
            'id' => '2',
            'name' => '进口'
        )
    );

    $array_option['picture'] = array(
        array(
            'id' => '0',
            'name' => '不限'
        ),
        array(
            'id' => '1',
            'name' => '只看有图'
        )
    );

    $gaslist = arr_gas();
    $i = 0;
    foreach ($gaslist as $k => $v) {
        $array_option['selectgas'][$i]['id'] = $i;
        $array_option['selectgas'][$i]['name'] = $v;
        $i++;
    }

    return json_encode($array_option);
}

// 城市数组
function select_city()
{
    global $db;
    $list = $db->row_select('area', "parentid=-1", 'id,name');
    foreach ($list as $key => $value) {
        $key++;
        $list[$key]['id'] = $value['id'];
        $list[$key]['name'] = trim($value['name']);
        $citylist = $db->row_select('area', "parentid=" . $value['id'], 'id,name', 0, 'orderid asc');
        foreach ($citylist as $k => $v) {
            //$k++;
            $citylist[$k]['name'] = trim($v['name']);
            $citylist[$k]['id'] = trim($v['id']);
        }
//        $citylist[0]['name'] = '不限';
//        $citylist[0]['id'] = 0;

        $list[$key]['city'] = $citylist;
    }
    $list[0]['name'] = "全国";
    $list[0]['id'] = 0;
    $list[0]['city'] = array(array('id' => 0, 'name' => '全国'));

    $list = array(
        'list' => $list
    );
//    echo "<pre>";
//    var_dump($list);
    return json_encode($list);
}

//提交评估信息
function submit_assess($mobilecode, $brand, $subbrand, $subsubbrand, $allname, $year, $month, $kilometre, $tel, $details, $aid, $cid, $question, $id)
{
    global $db;
    $post['p_contact_tel'] = $tel;
    $post['p_brand'] = $brand;
    $post['p_subbrand'] = $subbrand;
    $post['p_subsubbrand'] = $subsubbrand;
    $post['p_allname'] = $allname;
    $post['p_details'] = $details;
    $post['p_question'] = $question;
    $post['p_kilometre'] = $kilometre;
    $post['p_addtime'] = time();
    $post['p_year'] = $year;
    $post['p_month'] = $month;
    $post['mobilecode'] = $mobilecode;
    $post['aid'] = $aid;
    $post['cid'] = $cid;
    $post['id'] = $id;
    $rs = $db->row_insert('assesscars', $post);
    if (!$rs) $s = array(
        'succ' => 'false',
        'msg' => '失败'
    );
    else $s = array(
        'succ' => 'true',
        'msg' => '成功'
    );
    return json_encode($s);
}

//提交发布车源数据
function submit_cars($brand, $subbrand, $subsubbrand, $allname, $model, $emission, $gas, $year, $month, $surveydate, $insurancedate, $aid, $cid, $kilometre, $transmission, $color, $price, $details, $picone, $pictwo, $picthree, $picfour, $picfive, $picsix, $picseven, $piceight, $picnine, $username, $tel, $mobilecode, $uid, $ios, $carid)
{
    global $db;
    if ($uid == 0) {
        $data = $db->row_select_one('comparison', "mobilecode= '" . $mobilecode . "'");
        if (empty($data['mobilecode'])) {
            $post['mobilecode'] = $mobilecode;
            $post['mobilephone'] = $tel;
            $rs = $db->row_insert('comparison', $post);
        }
    }
    $post = array();
    $cardir = "upload/image/" . date("Ymd") . '/';
    if (!file_exists($cardir)) {
        mkdir("upload/image/" . date("Ymd"));
    }
    //新文件名
    $post['p_pics'] = '';
    if ($ios == 1) {
        $pics = $picone . ',' . $pictwo . ',' . $picthree . ',' . $picfour . ',' . $picfive . ',' . $picsix . ',' . $picseven . ',' . $piceight . ',' . $picnine;
        $pics = explode(',', $pics);
        foreach ($pics as $key => $value) {
            if (!empty($value)) {
                $pic = explode('.', $value);
                if ($key == 0) {
                    $dirname = substr($pic[0], 1, 8);
                    $post['p_mainpic'] = "/upload/image/" . $dirname . "/" . $value;
                } else {
                    $dirname = substr($pic[0], 0, 8);
                }
                $picname = $pic[0] . '_small' . '.jpg';
                $smallname = "upload/image/" . $dirname . "/" . $picname;
                // copy("upload/file/".$mobilecode."/".$picname,$smallname);
                require_once INC_DIR . 'img.class.php';
                $t = new ThumbHandler();
                $t->setSrcImg($smallname);
                $t->setDstImg($smallname);
                $t->createImg(200, 200);

                // copy("upload/file/".$mobilecode."/".$value,"upload/image/".$dirname."/".$value);
                $post['p_pics'] .= "/upload/image/" . $dirname . "/" . $value . "|";
            }
        }
        $post['p_pics'] = substr($post['p_pics'], 0, -1);
    } else {
        $pics = $picone . ',' . $pictwo . ',' . $picthree . ',' . $picfour . ',' . $picfive . ',' . $picsix . ',' . $picseven . ',' . $piceight . ',' . $picnine;
        $pics = explode(',', $pics);
        foreach ($pics as $key => $value) {
            if ($value != '') {
                $rand_str = rand(10000, 99999);
                $xmlstr = base64_decode($value);
                $pictures = $cardir . date("YmdHis") . '_' . $rand_str . '.' . 'jpg';
                $file = fopen($pictures, "w"); //打开文件准备写入
                fwrite($file, $xmlstr); //写入
                fclose($file); //关闭
                /*if (isImage($pictures) == false) {
                    unlink($pictures);
                    $s = array(
                        'succ' => 'false',
                        'msg' => '图片类型不正确'
                    );
                    return json_encode($s);
                } else {*/
                $smallname = $cardir . date("YmdHis") . '_' . $rand_str . '_small' . '.jpg';
                copy($pictures, $smallname);
                require_once INC_DIR . 'img.class.php';
                $t = new ThumbHandler();
                $t->setSrcImg($smallname);
                $t->setDstImg($smallname);
                $t->createImg(200, 200);
                $pictures = '/' . $pictures;
                $post['p_pics'] .= $pictures . "|";
                if ($key == 0) {
                    $post['p_mainpic'] = $pictures;
                }
                //}
            }
        }
        $post['p_pics'] = substr($post['p_pics'], 0, -1);
    }
    $post['p_brand'] = $brand;
    $post['p_subbrand'] = $subbrand;
    $post['p_username'] = $username;
    $post['p_subsubbrand'] = $subsubbrand;

    if (!empty($post['p_subsubbrand'])) {
        $rs_brand = $db->row_select_one('brand', 'b_id=' . $post['p_subsubbrand']);
        $post['p_gas'] = $rs_brand['b_gas'];
        $post['p_transmission'] = $rs_brand['b_transmission'];
    }

    $post['p_model'] = $model;
    $post['p_emission'] = $emission;
    $post['p_allname'] = $allname;
    $post['p_details'] = $details;
    $post['p_year'] = $year;
    $post['p_month'] = $month;
    $post['p_kilometre'] = $kilometre;
    $post['p_color'] = $color;
    $post['p_price'] = $price;
    $post['p_addtime'] = $post['listtime'] = time();
    $post['p_surveydate'] = strtotime($surveydate);
    $post['p_insurancedate'] = strtotime($insurancedate);
    $post['p_gas'] = $gas;
    $post['p_transmission'] = $transmission;
    $post['aid'] = $aid;
    $post['cid'] = $cid;
    $post['uid'] = $uid;
    if ($uid == 0) {
        $post['p_username'] = $username;
        $post['p_tel'] = $tel;
        $post['mobilecode'] = $mobilecode;
        $post['isshow'] = 0;
    } else {
        $member = $db->row_select_one('member', "id='" . $uid . "'", 'isdealer');
        if ($member['isdealer'] == 1) {
            $post['isshow'] = 0;
        } else {
            $post['isshow'] = 1;
        }
    }

    include(INC_DIR . 'html.func.php');

    if ($carid == 0) {
        $rs = $db->row_insert('cars', $post);
        $insertid = $db->insert_id();
        html_cars($insertid);
    } else {
        $rs = $db->row_update('cars', $post, "p_id=" . $carid);
        html_cars($carid);
    }

    if (!$rs) {
        $s = array(
            'succ' => 'false',
            'msg' => '失败'
        );
    } else {
        $s = array(
            'succ' => 'true',
            'msg' => '成功',
            'mobilecode' => $mobilecode
        );
    }
    return json_encode($s);
}

////上传图片
//function submit_upload($mobilecode) {
//    if (!empty($_FILES['file']['name'])) {
//        if ($_FILES['file']['tmp_name'] != '') {
//            $rand_str = rand(10000, 99999);
//            $cardir = "upload/file/" . $mobilecode;
//            if (!file_exists($cardir)) {
//                mkdir("upload/file/" . $mobilecode);
//            }
//            if ($_FILES['file']['name'] == '0.jpg') {
//                $newname = '1' . date("YmdHis") . '_' . $rand_str . '.' . 'jpg';
//                copy($_FILES['file']['tmp_name'], "upload/file/" . $mobilecode . "/" . $newname);
//            } else {
//                $newname = date("YmdHis") . '_' . $rand_str . '.' . 'jpg';
//                copy($_FILES['file']['tmp_name'], "upload/file/" . $mobilecode . "/" . $newname);
//            }
//            $pname = "upload/file/" . $mobilecode . "/" . $newname;
//            /*if (isImage($pname) == false) {
//                $status = array(
//                    'succ' => 'false',
//                    'msg' => '您上传的文件不是真实图片'
//                );
//                unlink($newname);
//                return json_encode($status);
//            } else {*/
//                $picname = explode('.', $newname);
//                $smallname = $picname[0] . '_small' . '.jpg';
//                copy($_FILES['file']['tmp_name'], "upload/file/" . $mobilecode . "/" . $smallname);
//                $pic_str = $newname;
//                $p_pics = '/upload/image/' . date("Ymd") . '/' . $newname;
//                //	$smallpic=$smallname;
//                $status = array(
//                    'succ' => 'true',
//                    'pic' => $pic_str,
//                    'p_pics' => $p_pics
//                );
//            //}
//        }
//    } else {
//        $status = array(
//            'succ' => 'false',
//            'msg' => '上传失败'
//        );
//    }
//    return json_encode($status);
//}


//上传图片
function submit_upload($mobilecode)
{
    if (!empty($_FILES['file']['name'])) {
        if ($_FILES['file']['tmp_name'] != '') {
            $rand_str = rand(10000, 99999);
//            $cardir = "upload/file/" . $mobilecode;
//            if (!file_exists($cardir)) {
//                mkdir("upload/file/" . $mobilecode);
//            }
//            if ($_FILES['file']['name'] == '0.jpg') {
//                $newname = '1' . date("YmdHis") . '_' . $rand_str . '.' . 'jpg';
//                copy($_FILES['file']['tmp_name'], "upload/file/" . $mobilecode . "/" . $newname);
//            } else {
//                $newname = date("YmdHis") . '_' . $rand_str . '.' . 'jpg';
//                copy($_FILES['file']['tmp_name'], "upload/file/" . $mobilecode . "/" . $newname);
//            }
//            $pname = "upload/file/" . $mobilecode . "/" . $newname;
            $cardir = "upload/image/" . date("Ymd");
            if (!file_exists($cardir)) {
                mkdir("upload/image/" . date("Ymd"));
            }
            if ($_FILES['file']['name'] == '0.jpg') {
                $newname = '1' . date("YmdHis") . '_' . $rand_str . '.' . 'jpg';
                copy($_FILES['file']['tmp_name'], "upload/image/" . date("Ymd") . "/" . $newname);
            } else {
                $newname = date("YmdHis") . '_' . $rand_str . '.' . 'jpg';
                copy($_FILES['file']['tmp_name'], "upload/image/" . date("Ymd") . "/" . $newname);
            }
            $pname = "upload/image/" . date("Ymd") . "/" . $newname;
            /*if (isImage($pname) == false) {
                $status = array(
                    'succ' => 'false',
                    'msg' => '您上传的文件不是真实图片'
                );
                unlink($newname);
                return json_encode($status);
            } else {*/
            $picname = explode('.', $newname);
            $smallname = $picname[0] . '_small' . '.jpg';
            $p_pics = '/upload/image/' . date("Ymd") . '/' . $newname;
            // copy($_FILES['file']['tmp_name'], "upload/image/" . $mobilecode . "/" . $smallname);
            copy($_FILES['file']['tmp_name'], "upload/image/" . date("Ymd") . "/" . $smallname);
            $pic_str = $newname;
            //	$smallpic=$smallname;
            $status = array(
                'succ' => 'true',
                'pic' => $pic_str,
                'p_pics' => $p_pics
            );
            //}
        }
    } else {
        $status = array(
            'succ' => 'false',
            'msg' => '上传失败'
        );
    }
    return json_encode($status);
}


//返回车源对比信息
function select_compcar($ids)
{
    global $db;
    $list = $db->row_select('cars', "p_id in" . '(' . $ids . ')');
    return json_encode($list);
}

//插入我的手机uid(我的车源收藏)
function insert_mycarsmobilecode($uid, $carid)
{
    global $db;
    $iscollect = $db->row_select_one('collectcars', 'p_id=' . $carid . ' and uid= "' . $uid . '"');
    $post['uid'] = $uid;
    $post['p_id'] = $carid;
    if (!$iscollect) {
        $rs = $db->row_insert('collectcars', $post);
        if (!$rs) $s = array(
            'succ' => 'false',
            'msg' => '失败'
        );
        else $s = array(
            'succ' => 'true',
            'msg' => '成功'
        );
    } else {
        $rs = $db->row_delete('collectcars', 'p_id=' . $carid . ' and uid=' . '"' . $uid . '"');
        if (!$rs) $s = array(
            'succ' => 'false',
            'msg' => '失败'
        );
        else $s = array(
            'succ' => 'true',
            'msg' => '成功'
        );
    }
    return json_encode($s);
}

//批量删除车源收藏
function del_mycarsmobilecode($uid, $carid)
{
    global $db;
    $rs = $db->row_delete('collectcars', "p_id in (" . $carid . ") and uid= " . $uid);
    if (!$rs) {
        $s = array(
            'succ' => 'false',
            'msg' => '失败');
    } else {
        $s = array(
            'succ' => 'true',
            'msg' => '成功'
        );
    }
    return json_encode($s);
}

//插入我的手机uid(我的经销商收藏)
function insert_mydealermobilecode($uid, $dealerid)
{
    global $db;
    $iscollect = $db->row_select_one('collectmember', 'dealerid=' . $dealerid . ' and uid= "' . $uid . '"');
    $post['dealerid'] = $dealerid;
    $post['uid'] = $uid;
    if (!$iscollect) {
        $rs = $db->row_insert('collectmember', $post);
        if (!$rs) $s = array(
            'succ' => 'false',
            'msg' => '失败'
        );
        else $s = array(
            'succ' => 'true',
            'msg' => '成功'
        );
    } else {
        $rs = $db->row_delete('collectmember', 'uid=' . $uid . ' and dealerid=' . '"' . $dealerid . '"');
        if (!$rs) $s = array(
            'succ' => 'false',
            'msg' => '失败'
        );
        else $s = array(
            'succ' => 'true',
            'msg' => '成功'
        );
    }
    return json_encode($s);
}

//批量删除车源收藏
function del_mydealermobilecode($uid, $dealerid)
{
    global $db;
    $rs = $db->row_delete('collectmember', "dealerid in (" . $dealerid . ") and uid= " . $uid);
    if (!$rs) {
        $s = array(
            'succ' => 'false',
            'msg' => '失败');
    } else {
        $s = array(
            'succ' => 'true',
            'msg' => '成功'
        );
    }
    return json_encode($s);
}

//插入我的手机mobilecode(我的对比车源信息)
function insert_comparmobilecode($id, $mobilecode)
{
    global $db;
    $post['mobilecode'] = $mobilecode;
    $rs = $db->row_insert('contrastcars', $post, 'id=' . $id);
    if (!$rs) $s = array(
        'succ' => 'false',
        'msg' => '失败'
    );
    else $s = array(
        'succ' => 'true',
        'msg' => '成功'
    );
    return json_encode($s);
}

//返回我的评估车源
function select_ascars($id, $mobilecode)
{
    global $db;
    $orderby = 'p_id';
    $where = ' mobilecode=' . $mobilecode . ' and p_id=' . $id;
    $page = !empty($page) ? $page : 1;
    include(INC_DIR . 'Page.class.php');
    $Page = new Page($db->tb_prefix . 'assesscars', $where, '*', '30', $orderby);
    $listnum = $Page->total_num;
    $list = $Page->get_data();
    foreach ($list as $key => $value) {
        $list[$key]['p_id'] = $value['p_id'];
        $list[$key]['p_contact_name'] = $value['p_contact_name'];
        $list[$key]['p_contact_tel'] = $value['p_contact_tel'];
        $list[$key]['p_subbrand '] = $value['p_subbrand'];
        $list[$key]['p_name'] = $value['p_name'];
        $list[$key]['p_keyword'] = $value['p_keyword'];
        $list[$key]['p_transmission'] = $value['p_transmission'];
        $list[$key]['p_year'] = $value['p_year'];
        $list[$key]['p_details'] = $value['p_details'];
        $list[$key]['p_model'] = $value['p_model'];
        $list[$key]['p_addtime'] = $value['p_addtime'];
        $list[$key]['p_pics'] = WEB_DOMAIN . $value['p_pics'];
        $list[$key]['p_mainpic'] = WEB_DOMAIN . $value['p_mainpic'];
        $list[$key]['p_month '] = $value['p_month'];
        $list[$key]['p_gas '] = $value['p_gas'];
        $list[$key]['p_price '] = $value['p_price'];
        $list[$key]['p_kilometre '] = $value['p_kilometre'];
        $list[$key]['isshow'] = $value['isshow'];
        unset($list[$key]['p_id']);
        unset($list[$key]['p_contact_name']);
        unset($list[$key]['p_contact_tel']);
        unset($list[$key]['p_subbrand']);
        unset($list[$key]['p_name']);
        unset($list[$key]['p_keyword']);
        unset($list[$key]['p_transmission']);
        unset($list[$key]['p_year']);
        unset($list[$key]['p_details']);
        unset($list[$key]['p_model']);
        unset($list[$key]['p_addtime']);
        unset($list[$key]['p_pics']);
        unset($list[$key]['p_mainpic']);
        unset($list[$key]['p_month']);
        unset($list[$key]['p_gas']);
        unset($list[$key]['p_price']);
        unset($list[$key]['p_kilometre']);
        unset($list[$key]['isshow']);
    }
    $page_arr = $Page->api_page();
    $myassesscars = array(
        'page' => $page_arr,
        'list' => $list
    );
    return json_encode($myassesscars);
}

//返回我的经销商收藏
function select_dealer($uid)
{
    global $db;
    $orderby = '';
    $list = $db->row_select('collectmember', "uid=" . $uid);
    foreach ($list as $key => $value) {
        $user = $db->row_select_one('member', "id=" . $value['dealerid']);
        $list[$key]['name'] = $user['username'];
        $list[$key]['tel'] = $user['mobilephone'];
        $publisholdcars = count($db->row_select('cars', "uid=" . $value['dealerid'], 'p_id'));
        $list[$key]['publisholdcars'] = $publisholdcars;
        $suoldcars = count($db->row_select('cars', "uid=" . $value['dealerid'] . ' and issell=1 ', 'p_id'));
        $list[$key]['suoldcars'] = $suoldcars;
        $list[$key]['usertype'] = "商家";
        $list[$key]['company'] = $user['company'];
        $list[$key]['address'] = $user['address'];
        if ($user['shoptype'] == 1) {
            $list[$key]['shoptypename'] = "经纪公司";
        } else if ($user['shoptype'] == 2) {
            $list[$key]['shoptypename'] = "4S店";
        } else if ($user['shoptype'] == 3) {
            $list[$key]['shoptypename'] = "综合经销商";
        } else {
            $list[$key]['shoptypename'] = "公司经营";
        }
    }
    $mycollectmember = array(
        'list' => $list
    );
    return json_encode($mycollectmember);
}

//二手车经销商车源
function  dealer_cars($uid, $status, $page)
{
    global $db;
    $orderby = '';
    $where = "isshow=1 and uid=" . $uid;
    if (!empty($status)) {
        switch ($status) {
            case 1:
                $orderby .= "listtime desc";
                break;

            case 2:
                $orderby = "  p_price asc";
                break;

            case 3:
                $orderby = "  p_price desc";
                break;

            case 4:
                $orderby = "  p_kilometre ";
                break;

            case 5:
                $orderby = "  p_year desc, p_month desc";
                break;
        }
    }
    $page = !empty($page) ? $page : 1;
    include(INC_DIR . 'Page.class.php');
    $Page = new Page($db->tb_prefix . 'cars', $where, 'uid,p_id,p_allname,p_price,p_color,p_gas,p_kilometre,p_year,p_month,p_mainpic,listtime', '10', $orderby);
    $listnum = $Page->total_num;
    $list = $Page->get_data();
    foreach ($list as $key => $value) {
        $list[$key]['id'] = $value['p_id'];
        $list[$key]['carname'] = $value['p_allname'];
        $list[$key]['price'] = $value['p_price'];
        $list[$key]['color'] = $value['p_color'];
        $list[$key]['gas'] = $value['p_gas'];
        $list[$key]['kilometre'] = $value['p_kilometre'];
        $list[$key]['regdate'] = $value['p_year'] . "年" . $value['p_month'] . '月';
        //$list[$key]['mainpic'] = "http://test.simcms.net".$value['p_mainpic'];
        if (!empty($value['p_mainpic'])) {
            $pic = explode(".", $value['p_mainpic']);
            $list[$key]['mainpic'] = WEB_DOMAIN . $pic[0] . "_small" . "." . $pic[1];
            //$list[$key]['mainpic'] = WEB_DOMAIN.$value['p_mainpic'];      
        }
        $list[$key]['listtime'] = date('Y-m-d', $value['listtime']);
        if (!empty($value['cid'])) {
            $area = $db->row_select_one('area', "id=" . $value['cid'], 'name');
            $list[$key]['city'] = $area['name'];
        } else {
            $list[$key]['city'] = "";
        }
        // 商家信息
        if (!empty($value['uid'])) {
            $user = $db->row_select_one('member', 'id=' . $value['uid'], 'isdealer');
            if ($user['isdealer'] == 2) {
                $list[$key]['usertype'] = "商家";
            } else {
                $list[$key]['usertype'] = "个人";
            }
        } else {
            $list[$key]['usertype'] = "个人";
        }
        unset($list[$key]['p_id']);
        unset($list[$key]['p_allname']);
        unset($list[$key]['p_price']);
        unset($list[$key]['p_color']);
        unset($list[$key]['p_gas']);
        unset($list[$key]['p_kilometre']);
        unset($list[$key]['p_year']);
        unset($list[$key]['p_month']);
        unset($list[$key]['p_mainpic']);
        unset($list[$key]['cid']);
    }
    $page_arr = $Page->api_page();
    $carlist = array(
        'page' => $page_arr,
        'list' => $list
    );
    return json_encode($carlist);
}

/*app进入广告*/
function indexad($appid, $appkey)
{
    global $db;
    $list = $db->row_select_one('ad', 'id=56', 'pic');
    $array_check = array('appid' => 'baisen', 'appkey' => 'baisennjkhghkjhgbvu7y7y8f5d3');
    if ($appid == $array_check['appid'] and $appkey == $array_check['appkey']) {
        $tokendata = $db->row_select_one('token', "id=1");
        $tokenvalue = array('token' => $tokendata['token'], 'pic' => WEB_DOMAIN . $list['pic'], 'optionversion' => 1, 'version' => 11);
    } else {
        $tokenvalue = array('token' => '', 'pic' => WEB_DOMAIN . $list['pic']);
    }
    $jsonlist = json_encode($tokenvalue);
    return $jsonlist;
}

//更新版本
function update_version($ios)
{
    global $version_android_arr;
    if ($ios == 1) {
        $version_arr = array(
            'versioncode' => '9',
            'isforceupdate' => '1',
            'updatecontent' => '',
            'apkname' => '车三顺',
            'downloadurl' => 'http://www.chesunshun.com/app/ios/phpusedcar.ipa',
            'versionname' => '201503'
        );
    } else {
        $version_arr = $version_android_arr;
//        $version_arr = array(
//            'versioncode' => '1',
//            'isforceupdate' => '1',
//            'updatecontent' => '',
//            'apkname' => '车三顺',
//            'downloadurl' => 'http://www.chesunshun.com/android/CheSanShun.apk',
//            'versionname' => '1'
//        );
    }
    return json_encode($version_arr);
}

//删除车
function deletecars($carid, $uid, $mobilecode)
{
    global $db;
    if ($mobilecode != 0) {
        $rs = $db->row_delete('cars', 'p_id=' . $carid . ' and mobilecode=' . $mobilecode);
    } else {
        $rs = $db->row_delete('cars', 'p_id=' . $carid . ' and uid=' . $uid);
    }
    if (!$rs) {
        $s = array('succ' => 'false', 'msg' => '失败');
    } else {
        $s = array('succ' => 'true', 'msg' => '成功');
    }
    return json_encode($s);
}

//售出
function sellcars($carid, $uid, $mobilecode)
{
    global $db;

    if ($mobilecode != 0) {
        $rs = $db->row_update('cars', array('issell' => 1), 'p_id=' . $carid . ' and mobilecode=' . $mobilecode);
    } else {
        $rs = $db->row_update('cars', array('issell' => 1), 'p_id=' . $carid . ' and uid=' . $uid);
    }
    if (!$rs) {
        $s = array('succ' => 'false', 'msg' => '失败');
    } else {
        $s = array('succ' => 'true', 'msg' => '成功');
    }
    return json_encode($s);
}


//车源评估
function tel_rapidasscars($subsubbrand, $mk, $reyear, $remonth)
{
    global $db;
    $arrt = '';
    $smk = 30;
    $sterm = 180;
    $year = date('Y', time());
    $month = date('m', time());
    $term = ($year - $reyear) * 12 + $month - $remonth;
    $data = $db->row_select_one('brand', "b_id='" . $subsubbrand . "'");
    //新车指导价
    $guideprice = $data['zd_price'];
    // 判断是否传过来综合参数
    $xiterm = round($term / 12);
    $mk = $mk > ($xiterm * 60000) ? ($xiterm * 60000) : $mk;
    if ($mk >= $smk) {
        $gl = 0.15;
    } else {
        $gl = $mk / $smk;
    } //超过了规定公里数 该车的残留价格为0.15 以不同的车残留价格市场而定
    if ($term >= $sterm) {
        $term = $sterm;
        $cx = 0.15;
    } else {
        $cx = $term / $sterm;
    } //超过了使用年限 该车的市场价格0.15 以不同的车残留价格市场而定
    if ($arrt) {
        $ratio = ($arrt['0'] * 30 / 100) + ($arrt['1'] * 25 / 100) + ($arrt['2'] * 20 / 100) + ($arrt['3'] * 15 / 100) + ($arrt['4'] * 10 / 100); //综合成新率
    } else {
        $ratio = tel_xianarrt($term, $sterm);
    }
    $newness = ((1 - $gl) + (1 - $cx)) / 2; //最后的成新率
    $price = round(ceil($newness * $ratio * $guideprice), 2);

    $list = array('price' => $price, 'newcarprice' => $guideprice);

    return json_encode($list);

}

//如果没有$arrt值为空就加载这个数组对应的
function tel_xianarrt($term, $sterm)
{
    $arr8 = array('0.8', '0.7', '0.6', '0.5', '0.4', '0.3', '0.25', '0.2');
    $arr10 = array('0.8', '0.7', '0.6', '0.5', '0.4', '0.35', '0.3', '0.25', '0.2');
    $arr15 = array('0.8', '0.7', '0.65', '0.6', '0.55', '0.5', '0.45', '0.4', '0.35', '0.3', '0.27', '0.24', '0.22', '0.2');
    $xiterm = round($term / 12);
    if ($xiterm > '0') {
        $xiterm = $xiterm - 1;
    }
    if ($sterm == '96') {
        if ($xiterm >= 8) {
            return 0.2;
        }
        return $arr8["$xiterm"];
    } elseif ($sterm == '120') {
        if ($xiterm >= 10) {
            return 0.2;
        }
        return $arr10["$xiterm"];
    } else {
        if ($xiterm >= 15) {
            return 0.2;
        }
        return $arr15["$xiterm"];
    }
}

/**
 * PHP DES 加密程式
 *
 * @param $key 密鑰（八個字元內）
 * @param $encrypt 要加密的明文
 * @return string 密文
 */
function encrypt($key, $encrypt)
{
    // 根據 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 加入 Padding
    $block = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $pad = $block - (strlen($encrypt) % $block);
    $encrypt .= str_repeat(chr($pad), $pad);

    // 不需要設定 IV 進行加密
    $passcrypt = mcrypt_encrypt(MCRYPT_DES, $key, $encrypt, MCRYPT_MODE_ECB);
    return base64_encode($passcrypt);
}

/**
 * PHP DES 解密程式
 *
 * @param $key 密鑰（八個字元內）
 * @param $decrypt 要解密的密文
 * @return string 明文
 */
function decrypt($key, $decrypt)
{
    // 不需要設定 IV
    $str = mcrypt_decrypt(MCRYPT_DES, $key, base64_decode($decrypt), MCRYPT_MODE_ECB);

    // 根據 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 移除 Padding
    $pad = ord($str[strlen($str) - 1]);
    return substr($str, 0, strlen($str) - $pad);
}

/**
 * 获取攻略分类
 */
function get_news()
{
    global $db;
    $list = $db->row_select('news_category', 'isshow=1 and newsshow=1', 'catid,catname', '', '');
    return json_encode($list);
}


/**
 * 获取攻略分类内容
 * @param $id
 */
function get_helplist($id, $type)
{
    global $db;
    if (!in_array($type, array(1, 2))) {
        $type = 1;
    }
    if ($type == 1) {
        $list = $db->row_select('news', 'catid=' . $id . ' and isshow=1', 'n_id,n_title', '', 'n_id desc');
        return json_encode($list);
    }
    if ($type == 2) { //公告
        $list = $db->row_select_one('news', 'catid=' . $id . ' and isshow=1 and n_closetime>' . time(), 'n_id,n_title', 'n_id desc', '');
        if ($list) {
            return json_encode(array('succ' => true, 'info' => $list));
        } else {
            return json_encode(array('succ' => false));
        }
    }

}

/**
 * 获取攻略分类内容详情
 */
function get_typelist($id)
{
    global $db;
    $list = $db->row_select_one('news', 'n_id=' . $id, 'n_title,n_info,n_addtime,n_pic,n_hits', '', '');
    $list['n_info'] = htmlspecialchars_decode($list['n_info']);
    $parem = 'src="http://' . $_SERVER['HTTP_HOST'] . '/upload/image';
    $list['n_info'] = preg_replace('/src=\"\/upload\/image/', $parem, $list['n_info']);
    return json_encode($list);
}

/**
 * get_User_Subscribe_NewNum
 * @param $uid 会员id
 * 获取用户订阅总新纪录数量
 * @return json (array('number'=>'0'))
 */
function get_User_Subscribe_NewNum($uid)
{
    global $db, $db_config;
    $sql = "SELECT sum(number) as number FROM {$db_config['TB_PREFIX']}rule_count WHERE mid=$uid";
    $result = $db->row_query_one($sql);
    return json_encode($result);
}

/**
 * get_User_Subscribe_Rule_List
 * @param $uid 会员id
 * 获取用户订阅规则列表，包含每个规则的新纪录数
 * @return json
 */
function get_User_Subscribe_Rule_List($uid)
{
    global $db, $db_config;
    $sql = "SELECT mr.*,rc.number  FROM {$db_config['TB_PREFIX']}member_rules mr left join  {$db_config['TB_PREFIX']}rule_count rc on mr.id=rc.r_id WHERE mr.mid=$uid";
    $result = $db->row_query($sql);
    return json_encode($result);
}

/**
 * set_Subscribe_Rule_Newnum_Clean
 * @param $uid 会员id
 * 用户点击查看后，清除规则新纪录数
 * @return json
 */
function set_Subscribe_Rule_Newnum_Clean($uid)
{
    global $db;
    $rid = $_REQUEST['rid']; //规则id
    if (empty($rid)) {
        $result = array('succ' => 'false', 'msg' => '参数错误！');
    } else {
        $sql = $db->sql_update('rule_count', array('number' => 0), "r_id=$rid and mid=$uid");
        $db->query($sql);
        $result = array('succ' => 'true', 'msg' => '操作成功！');
    }
    return json_encode($result);
}

/**
 * add_Subscribe_Rule
 * 添加订阅规则
 * @param $uid
 */
function add_Subscribe_Rule($uid)
{
    global $db;
    $brand_id = isset($_REQUEST['brand_id']) && $_REQUEST['brand_id'] ? intval(abs($_REQUEST['brand_id'])) : 0;
    $brand_name = isset($_REQUEST['brand_name']) && $_REQUEST['brand_name'] ? $_REQUEST['brand_name'] : '全部品牌';
    $cid = isset($_REQUEST['cid']) && $_REQUEST['cid'] ? intval(abs($_REQUEST['cid'])) : 0;
    $city_name = isset($_REQUEST['city_name']) && $_REQUEST['city_name'] ? $_REQUEST['city_name'] : '全国';
    $lower_price = isset($_REQUEST['lower_price']) && $_REQUEST['lower_price'] ? floatval(abs($_REQUEST['lower_price'])) : 0.00;
    $higher_price = isset($_REQUEST['higher_price']) && $_REQUEST['higher_price'] ? floatval(abs($_REQUEST['higher_price'])) : 1000000.00;
    if ($higher_price < $lower_price) {
        $result = array('succ' => 'false', 'msg' => '价格参数错误！');
        return json_encode($result);
    }

    //计算总订阅规则数
    $count = $db->row_count('member_rules', "mid=$uid");
    if ($count == 10) {
        $result = array('succ' => 'false', 'msg' => '规则条数已达上限！');
        return json_encode($result);
    }

    $rs = $db->row_select_one('member_rules', "mid=$uid and brand_id=$brand_id and cid =$cid and lower_price=$lower_price and higher_price=$higher_price", 'id');
    if ($rs) {
        $result = array('succ' => 'false', 'msg' => '已存在此规则！');
        return json_encode($result);
    }
    $db->row_insert('member_rules', array('mid' => $uid, 'brand_id' => $brand_id, 'cid' => $cid, 'lower_price' => $lower_price, 'higher_price' => $higher_price, 'brand_name' => $brand_name, 'city_name' => $city_name));
    $r_id = $db->insert_id();
    $rules['r_id'] = $r_id;
    $rules['mid'] = $uid;
    $rules['number'] = 0;
    $db->row_insert('rule_count', $rules);
    unset($rules);
    $result = array('succ' => 'true', 'msg' => '操作成功！');
    return json_encode($result);

}

/**
 * update_Subscribe_Rule
 * 更新订阅规则
 * @param $uid
 */
function update_Subscribe_Rule($uid)
{
    global $db;
    $r_id = isset($_REQUEST['r_id']) && $_REQUEST['r_id'] ? intval(abs($_REQUEST['r_id'])) : 0;
    $brand_id = isset($_REQUEST['brand_id']) && $_REQUEST['brand_id'] ? intval(abs($_REQUEST['brand_id'])) : 0;
    $brand_name = isset($_REQUEST['brand_name']) && $_REQUEST['brand_name'] ? $_REQUEST['brand_name'] : '全部品牌';
    $cid = isset($_REQUEST['cid']) && $_REQUEST['cid'] ? intval(abs($_REQUEST['cid'])) : 0;
    $city_name = isset($_REQUEST['city_name']) && $_REQUEST['city_name'] ? $_REQUEST['city_name'] : '全国';
    $lower_price = isset($_REQUEST['lower_price']) && $_REQUEST['lower_price'] ? floatval(abs($_REQUEST['lower_price'])) : 0.00;
    $higher_price = isset($_REQUEST['higher_price']) && $_REQUEST['higher_price'] ? floatval(abs($_REQUEST['higher_price'])) : 1000000.00;
    if ($higher_price < $lower_price) {
        $result = array('succ' => 'false', 'msg' => '价格参数错误！');
        return json_encode($result);
    }
    if ($r_id == 0) {
        $result = array('succ' => 'false', 'msg' => '规则参数错误！');
        return json_encode($result);
    }
    $db->row_update('member_rules', array('brand_id' => $brand_id, 'cid' => $cid, 'lower_price' => $lower_price, 'higher_price' => $higher_price, 'brand_name' => $brand_name, 'city_name' => $city_name), "id=$r_id and mid=$uid");
    $rules['number'] = 0;
    $db->row_update('rule_count', $rules, "r_id=$r_id");
    unset($rules);
    $result = array('succ' => 'true', 'msg' => '操作成功！');
    return json_encode($result);
}

/**
 * delete_Subscribe_Rule
 * 删除规则
 * @param $uid
 */
function delete_Subscribe_Rule($uid)
{
    global $db;
    $r_id = isset($_REQUEST['r_id']) && $_REQUEST['r_id'] ? intval(abs($_REQUEST['r_id'])) : 0;
    if ($r_id == 0) {
        $result = array('succ' => 'false', 'msg' => '规则参数错误！');
        return json_encode($result);
    }
    $db->row_delete('member_rules', "id=$r_id and mid=$uid");
    $db->row_delete('rule_count', "r_id=$r_id and mid=$uid");
    $result = array('succ' => 'true', 'msg' => '操作成功！');
    return json_encode($result);
}

/**
 * sms_send
 * @param string $tel
 * @param int $type 1 注册，2==找回密码
 * @return string
 */
function sms_send($tel = '', $type = 1)
{
    global $db;
    if (empty($tel) || !preg_match('/^1[3-9]\d{9}$/', $tel)) return json_encode(array('succ' => 'false', 'msg' => '手机号参数错误！'));
    if (empty($type)) $type = 1;
    $sms_status = sms_send_status($tel, $type);
    if (is_array($sms_status)) return json_encode($sms_status);
    $code = get_code(6);
    if (sendSMS($tel, $code)) {
        $time = time();
        $db->row_insert('sms_records', array('mobile' => $tel, 'code' => $code . '_' . $time, 'type' => $type,'dateline'=>$time));
        return json_encode(array('succ' => 'true', 'msg' => '发送成功！', 'code' => $code));
    }

    $db->row_insert('sms_records', array('mobile' => $tel,  'type' => 0,'dateline'=>time()));
    return json_encode(array('succ' => 'false', 'msg' => '发送失败！'));
}

function check_sms($mobile, $code, $type = 1)
{
    global $db;
    if (empty($code) || empty($mobile)) {
        $status = array(
            'succ' => 'false',
            'msg' => '手机号、验证码不可为空'
        );
        return json_encode($status);
    }
    $type = in_array($type, array(1, 2)) ? $type : 1;

    $record = $db->row_select_one('sms_records', "mobile= '$mobile' and type=$type", '*', 'id desc');
    if (!$record) return json_encode(array('succ' => 'false', 'msg' => '验证码不存在'));
    list($Code, $Time) = explode('_', $record['code']);
    if ($Code != $code) return json_encode(array('succ' => 'false', 'msg' => '验证码错误'));
    if (time() - intval($Time) > SMS_CODE_TIME) return json_encode(array('succ' => 'false', 'msg' => '验证码已过期'));
    $code = get_code(6);
    $content = "您的密码被重置为：" . $code . "；请尽快登陆修改密码";
    if ($type == 2 && sendSMS($mobile, $content)) {
        $rs = $db->row_update('member', array('password' => md5($code)), "mobilephone=" . $mobile);
        if ($rs) return json_encode(array('succ' => 'true', 'msg' => '修改密码成功！'));
        return json_encode(array('succ' => 'false', 'msg' => '修改密码失败！'));
    }
    return json_encode(array('succ' => 'true', 'msg' => '验证成功！'));
}

/**
 * update_user_device_tokens
 * 更新用户设备token
 * @param $uid
 * @param $token
 * @return string
 */
function update_user_device_tokens($uid, $token)
{
    global $db;
    if ($uid && $token) {
        $rs = $db->row_update('member', array('device' => $token), 'id=' . $uid);
        if ($rs) {
            $return = array('succ' => true, 'msg' => '操作成功');
        } else {
            $return = array('succ' => false, 'msg' => '操作失败');
        }
    } else {
        $return = array('succ' => false, 'msg' => '参数错误');
    }
    return json_encode($return);
}

/**
 * update_user_Im
 * 更新用户环信账号
 * @param $uid
 * @return bool
 */
function update_user_Im($uid)
{
    global $db;
    if ($uid == false) return false;
    $db->row_update('member', array('isIm' => 2), 'id=' . $uid);
}

/*
 * 更新用户头像
 */
function update_user_avatar($uid)
{
    global $db;
    if ($uid == false) return false;
    $rs = json_decode(submit_upload(''));
    if ($rs->succ == 'true') {
        $db->row_update('member', array('avatar' => $rs->p_pics), 'id=' . $uid);
        echo json_encode(array('avatar' => 'http://' . $_SERVER['HTTP_HOST'] . $rs->p_pics));
    }
    return false;
}

/*
 * get_user_info
 * 获取用户信息
*/
function get_user_info($tel)
{
    global $db;
    if ($tel) {
        $rs = $db->row_select_one('member', "mobilephone=" . $tel . "", 'avatar,nicname');
        if ($rs) {
            $rs['avatar'] = $rs['avatar'] != "''" ? 'http://' . $_SERVER['HTTP_HOST'] . $rs['avatar'] : '';;
            $return = array('succ' => true, 'user' => $rs);
        } else {
            $return = array('succ' => false, 'msg' => '无此用户信息');
        }
    } else {
        $return = array('succ' => false, 'msg' => '参数错误');
    }
    return json_encode($return);
}

?>